﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using JSC.Portal.Utils;
using System.IO;
using System.Xml;

namespace JSC.Portal.Web.Results
{
    public class RssResult : ActionResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            RssChannel channel = (RssChannel)context.Controller.ViewData.Model;
            // Rss feed writer code from http://aspnet.4guysfromrolla.com/articles/021804-1.aspx
            // Use an XmlTextWriter to write the XML data to a string...
            StringWriter sw = new StringWriter();
            XmlTextWriter writer = new XmlTextWriter(sw);
            writer.Formatting = Formatting.Indented;

            // write out 
            writer.WriteStartElement("rss");
            writer.WriteAttributeString("version", "2.0");
            writer.WriteAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/");

            // write out 
            writer.WriteStartElement("channel");

            // write out -level elements
            writer.WriteElementString("title", channel.Title);
            writer.WriteElementString("link", channel.Link);
            writer.WriteElementString("description", channel.Description);
            writer.WriteElementString("language", channel.Language);
            writer.WriteElementString("pubDate", channel.PubDate.ToUniversalTime().ToString("r"));
            writer.WriteElementString("lastBuildDate", channel.LastBuildDate.ToUniversalTime().ToString("r"));
            writer.WriteElementString("generator", channel.Generator);
            writer.WriteElementString("ttl", channel.Ttl.ToString());

            foreach (RssItem item in channel.RssItems)
            {
                // write out 
                writer.WriteStartElement("item");

                // write out -level information
                writer.WriteElementString("title", item.Title);
                // TODO: Only supports ID's in the pathinfo now...
                writer.WriteElementString("link", item.Link);
                writer.WriteElementString("description", item.Description);
                writer.WriteElementString("dc:creator", item.Author);
                writer.WriteElementString("pubDate", item.PubDate.ToUniversalTime().ToString("r"));
                writer.WriteElementString("category", item.Category);

                // write out 
                writer.WriteEndElement();
            }

            // write out 
            writer.WriteEndElement();

            // write out 
            writer.WriteEndElement();

            context.HttpContext.Response.Write(sw.ToString());
            writer.Close();
        }
    }
}
